/**
 * cn.ucox.web.framework.kits.RequestKit
 *
 * @author chenw
 * @create 16/3/21.09:45
 * @email javacspring@hotmail.com
 */

package cn.com.oceansoft.framework.kits;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author chenw
 * @create 16/3/21 09:45
 * @email javacspring@gmail.com
 */
public class RequestKit {

    /**
     * 判断是否为AJAX请求
     *
     * @param request HttpServletRequest
     * @return true是, 反之false
     */
    public static boolean isAjax(HttpServletRequest request) {
        return request != null && "XMLHttpRequest".equalsIgnoreCase(request.getHeader("X-Requested-With"));
    }

    public static boolean isAccessJson(HttpServletRequest request) {
        String accept = request.getHeader("Accept");
        return null != accept && accept.toLowerCase().contains("application/json");
    }
    /**
     * 获取springmvc所有注册的RequestMapping信息
     * @param request
     * @return
     */
    public static Map<RequestMappingInfo, HandlerMethod> getHandlerMethods(HttpServletRequest request){
        WebApplicationContext wc = (WebApplicationContext) request.getAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE);
        RequestMappingHandlerMapping bean = wc.getBean(RequestMappingHandlerMapping.class);
        Map<RequestMappingInfo, HandlerMethod> handlerMethods = bean.getHandlerMethods();
        return handlerMethods;
    }
}
